package com.usian.admin.gateway.filters;

import com.usian.utils.common.AppJwtUtil;
import io.jsonwebtoken.Claims;
import lombok.extern.log4j.Log4j2;
import org.apache.commons.lang3.StringUtils;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

//加入到spring容器中
@Component
@Log4j2
public class AuthorizeFilter implements GlobalFilter, Ordered {
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        //获取request和response对象
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();

        //判断请求路径是否为  /login/in
        if (request.getURI().getPath().contains("/login/in")) {
            //放行
            return chain.filter(exchange);
        }

        //获取请求头信息中的token
        String token = request.getHeaders().getFirst("token");
        //校验token是否存在
        if (StringUtils.isEmpty(token)) {
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            return response.setComplete();
        }

        try {
            //解析token中的内容
            Claims claims = AppJwtUtil.getClaimsBody(token);
            int i = AppJwtUtil.verifyToken(claims);
            if (i == 1 || i == 0) {
                //合法,则向header中重新设置userId
                Integer id = (Integer) claims.get("id");
                log.info("find userid:{} from uri:{}", id, request.getURI());
                //重新设置token到header中
                request.mutate().headers(httpHeaders -> {
                    httpHeaders.add("userId", id + "");
                }).build();

                //重新构建请求头信息
                exchange.mutate().request(request).build();
            }
        } catch (Exception e) {
            e.printStackTrace();
            //向客户端返回错误提示信息
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            return response.setComplete();
        }

        //放行
        return chain.filter(exchange);
    }


    //获取order的方法
    @Override
    public int getOrder() {
        return 0;
    }

}
